#include <WinSock.h>
#include <iostream>

SOCKET dbmsConnect(char * Server, unsigned short port)
{
	SOCKET sock;
	struct sockaddr_in serveraddr;		// Server address info
	struct hostent *host = NULL;		// Host name conversation function returned value
	char buf[100];						// WSA Error buffer
	int err;							// Returned values for various functions

	// WinSock Init
	WSADATA wsaData; // WinSock info
	if (WSAStartup(MAKEWORD(1,0), &wsaData) != 0) {
		MessageBox(0, "Can't load WinSock", "Error", 0);
		return FALSE;
	}

	// Create socket
	sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
	if (sock == INVALID_SOCKET) {
		MessageBox(0, "Create socket failed", "Error", 0);
		return -1;
	}

	// Fill in server address info
	serveraddr.sin_family = AF_INET;
	serveraddr.sin_port = htons(port);						// <----------------
	serveraddr.sin_addr.s_addr = inet_addr(Server);

	// Convert domain host name to IP address
	if (serveraddr.sin_addr.s_addr == INADDR_NONE) {
		MessageBox(0, "Converting host address", "Action", 0);
		host = gethostbyname(Server);
		if (host == NULL) {
			MessageBox(0, "Unable to resolve the host", "Error", 0);
			return -1;
		}
		CopyMemory(&serveraddr.sin_addr, host->h_addr_list, host->h_length);
	}

	// Connect to the server
	if (connect(sock, (struct sockaddr *)&serveraddr, sizeof(serveraddr)) == SOCKET_ERROR) {
		err = WSAGetLastError();
		sprintf(buf, "%d", err);
		MessageBox(0, "Error: Unable to connect.", "Error Code", 0);
		MessageBox(0, buf, "Error Code", 0);
		return -1;
	}

	return sock;
}

std::string dbmsQuery( char * sMessage, char * Server, unsigned short port)
{
	SOCKET sock;						// Server connetion socket

//	char *sMessage;						// Message that will be sent to server
	char szRecvBuff[1024];				// Buffer for received data

	int err;							// Returned values for various functions



	sock = dbmsConnect(Server, port);

	// Send data
	err = send(sock, sMessage, (int)strlen(sMessage), 0);
	if (err == SOCKET_ERROR) {
		MessageBox(0, "Send data failed", "Error", 0);
	}

	// Receive data
	err = recv(sock, szRecvBuff, 1024, 0);
	if (err == SOCKET_ERROR) {
		MessageBox(0, "Receive failed", "Error", 0);
	}

	szRecvBuff[err] = 0;

	closesocket(sock);
	WSACleanup();
	return szRecvBuff;
}